package com.bootdo.clouddo.controller.book;


import com.bootdo.clouddo.domain.book.BookContent;
import com.bootdo.clouddo.service.book.IBookContentService;
import com.bootdo.clouddo.utils.book.BookUtils;
import com.bootdo.clouddo.utils.book.HttpUtils;
import com.bootdo.clouddo.utils.R;
import com.bootdo.clouddo.utils.StringUtils;
import com.bootdo.clouddo.utils.common.ErrorCode;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/book/v1")
public class ReadController {

    @Autowired
    private IBookContentService contentService;

    @GetMapping("/read")
    public R read(String chapter, Integer siteId, Long bookId, String url) {
        try {
            if(StringUtils.isBlank(chapter) || StringUtils.isBlank(url) ||
                bookId == null || siteId == null) {
                return R.error(ErrorCode.INVALID_PARAMETERS);
            }
            BookContent bc = contentService.find(bookId, siteId, url);
            if(bc != null && StringUtils.isNotBlank(bc.getContent())) {
                System.out.println("read: " + bookId + " by db");
                return R.data(bc.getContent());
            }
            String chapterUrl = chapter.replace("[chapterid]", url);
            //chapterUrl = "http://www.iqiwx.com/book/7/7367/9045075.html";
            //siteId = "35";
            System.out.println("read: " + bookId + " by url");
            return R.data(BookUtils.getContent(chapterUrl, siteId));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return R.error();
    }

}
